﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Xml.Serialization;
using System.Xml;
using CrazyWorship1.ListenerService;
using System.IO;

namespace CrazyWorship1
{

    public class ScreenInfoList : ObservableCollection<ScreenInfo>, IXmlSerializable
    {
        public ScreenInfoList()
        {
        }
        public void Add(string clientUrl, DisplayInfo displayInfo)
        {
            this.Add(new ScreenInfo(clientUrl, displayInfo));
        }

        #region IXmlSerializable Members

        public ScreenInfo GetByClientUrl(string clientUrl,string deviceName)
        {
            foreach (ScreenInfo s in this)
            {
                if ((s.ClientUrl == clientUrl)&&(s.DeviceName==deviceName))
                    return s;
            }
            return null;
        }
        public static ScreenInfoList Load()
        {
            FileStream stream = new FileStream(ClientManager.screenInfoFile, FileMode.OpenOrCreate);
            XmlSerializer x = new XmlSerializer(typeof(ScreenInfoList));
            ScreenInfoList si = new ScreenInfoList();
            try
            {
               si = (ScreenInfoList)x.Deserialize(stream);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            stream.Close();
            return si;
        }
        public void Save()
        {
            XmlSerializer x = new XmlSerializer(typeof(ScreenInfoList));
            FileStream stream = new FileStream(ClientManager.screenInfoFile, FileMode.Create);
            x.Serialize(stream, this);
            stream.Close();
            //ds.WriteXml(clientsFile);
        }
        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(XmlReader reader)
        {

            reader.ReadStartElement("ScreenInfoList"); 
            reader.ReadStartElement("ScreenInfoList");
            if (reader.NodeType != XmlNodeType.EndElement)
            {
                while (reader.NodeType != XmlNodeType.EndElement)
                {
                    ScreenInfo c = new ScreenInfo();
                    c.ReadXml(reader);
                    this.Add(c);
                }
            }

                reader.ReadEndElement();
                reader.ReadEndElement();
            //  reader.MoveToContent();
        }

        public void WriteXml(XmlWriter writer)
        {
            writer.WriteStartElement("ScreenInfoList");
            foreach (ScreenInfo info in this)
            {
                ((IXmlSerializable)info).WriteXml(writer);
            }
            writer.WriteEndElement();

        }

        #endregion
    }
}
